<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js"></script>
    <style>
        #box {
            width: 400px;
            margin: 50px auto;
        }
    </style>
</head>
<body>
<div id="box">
    <form action="/addEmp" method="post" id="form">
        <input type="hidden" name="eid" id="eid"><br/>
        名字：<input type="text" name="ename" id="ename" placeholder="请输入名字"><br/>
        工资：<input type="text" name="salary" id="salary" placeholder="请输入员工工资"><br/>
        入职时间：<input type="date" name="workDate" id="workDate"><br/>
        性别：<input type="radio" name="esex" class="esex" value="男"> 男
        <input type="radio" name="esex" class="esex" value="女"> 女<br/>
        所属部门：<select name="deptid" id="dname"></select><br/>
        <input type="button" value="修改" id="addEmp">
    </form>
</div>

<script>
    $(document).ready(function () {
        $.ajax({
            type: "post",
            url: "/getdeptmes",
            data: {},
            success: function (res) {
                for (let resKey in res) {
                    $("#dname").append($("<option></option>").text(res[resKey].dname).val(res[resKey].deptid));
                }
                getEmployeeData()
            }
        });
        function getEmployeeData() {
            $.ajax({
                type: "post",
                url: "/getempbysession",
                data: {},
                success: function (res) {
                    $("#eid").val(res.eid);
                    $("#ename").val(res.ename);
                    $("#salary").val(res.salary);

                    // 回显日期
                    let workDate = res.workDate.split(' ')[0];
                    $("#workDate").val(workDate);

                    // 回显性别
                    $("input[name='esex'][value='" + res.esex + "']").prop("checked", true);

                    // 回显部门
                    $("#dname").val(res.deptid);
                }
            });
        }

        $("#addEmp").click(function () {
            $.ajax({
                type: "post",
                url: "/upEmp",
                data: {
                    "eid": $("#eid").val(),
                    "ename": $("#ename").val(),
                    "salary": $("#salary").val(),
                    "workDate": $("#workDate").val(),
                    "esex": $(".esex:checked").val(),
                    "deptid": $("#dname").val()
                },
                success: function (res) {
                    if (res == "true") {
                        window.location.href = "./employ2.html";
                    } else {
                        alert("修改失败");
                        location.href = "/";
                    }
                }
            });
        });
    });
</script>
</body>
</html>
